import axios from 'axios'
import {closeLoading, showLoading} from "@/core/utils/loading";
import {errorMsg, warningMsg} from "@/core/utils/message";
import Vue from "vue";
import {getToken, removeAllCache, setAdminVersion, setServerVersion} from "@/core/utils/storage";
import router from "@/core/router/router";

Vue.use(v => {
    v.prototype.$http = $http;
});

const $http = axios.create({
    timeout: 100 * 1000,
});

// 请求拦截  设置统一header
$http.interceptors.request.use(config => {
    showLoading(null);
    let url: any = config.url;
    let haveHttp = (url + "").indexOf("http://").toString() != "-1";
    let haveHttps = (url + "").indexOf("https://").toString() != "-1";
    config.headers['token'] = getToken();
    if (haveHttp || haveHttps) {
    } else {
        config.url = process.env.VUE_APP_SERVER_BASE_URL + url;
    }
    return config;
}, error => {
    return Promise.reject(error)
});

$http.interceptors.response.use(response => {
    let data: any = response.data;
    if (response.config.responseType && response.config.responseType == "blob") {
        closeLoading();
        return data;
    }

    if (!data.code) {
        return response;
    }

    if (data.code == "get_config_json") {
        return data;
    }

    //请求成功
    if (data.code == 200) {
    }
    //请求失败
    else if (data.code == 500) {
        errorMsg(data.message)
    }
    //强制重新登录
    else if (data.code.toString() == "555") {
        removeAllCache();
        warningMsg("登录状态已失效，请重新登录", 2000);
        setTimeout(() => {
            window.location.reload();
        }, 2000)
    }
    //请求失败
    else if (data.code.toString() == "400") {
        errorMsg(data.message)
    }
    //权限不足
    else if (data.code.toString() == "402") {
        router.push({path: "/"});
    }
    //管理端登录失效
    else if (data.code.toString() == "401") {
        warningMsg("登录已失效，请重新登录.");
    }
    //微信端登录失效
    else if (data.code.toString() == "4011") {
        warningMsg("登录已失效，请重新登录.");
    }
    closeLoading();
    return data;
}, error => {
    closeLoading();
    if (error.toString().indexOf("404")! - 1) {
        errorMsg("访问资源不存在");
        return;
    }
    errorMsg("操作失败：服务器暂未开启.");
});

export default $http

